package com.example.blogapi.controller;

import com.example.blogapi.model.Category;
import com.example.blogapi.service.CategoryService;
import com.example.blogapi.util.HttpUtil;
import com.example.blogapi.util.JsonUtil;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class CategoryController implements HttpHandler {
    private final CategoryService categoryService;

    public CategoryController() {
        this.categoryService = new CategoryService();
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        String path = exchange.getRequestURI().getPath();

        try {
            if (method.equals("OPTIONS")) {
                handleOptionsRequest(exchange);
            } else if (method.equals("GET") && path.matches("/api/categories/?")) {
                handleGetAllCategories(exchange);
            } else if (method.equals("GET") && path.matches("/api/categories/\\d+/?")) {
                handleGetCategoryById(exchange);
            } else if (method.equals("POST") && path.matches("/api/categories/?")) {
                handleCreateCategory(exchange);
            } else if (method.equals("PUT") && path.matches("/api/categories/\\d+/?")) {
                handleUpdateCategory(exchange);
            } else if (method.equals("DELETE") && path.matches("/api/categories/\\d+/?")) {
                handleDeleteCategory(exchange);
            } else {
                String response = JsonUtil.toJson(Map.of("error", "Not found"));
                HttpUtil.sendResponse(exchange, 404, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 500, response);
        }
    }

    private void handleOptionsRequest(HttpExchange exchange) throws IOException {
        HttpUtil.sendResponse(exchange, 200, "");
    }

    private void handleGetAllCategories(HttpExchange exchange) throws IOException, SQLException {
        List<Category> categories = categoryService.getAllCategories();
        String response = JsonUtil.toJson(categories);
        HttpUtil.sendResponse(exchange, 200, response);
    }

    private void handleGetCategoryById(HttpExchange exchange) throws IOException, SQLException {
        Long id = HttpUtil.extractIdFromPath(exchange.getRequestURI().getPath(), "/api/categories/(\\d+)/?");
        
        Category category = categoryService.getCategoryById(id);
        if (category != null) {
            String response = JsonUtil.toJson(category);
            HttpUtil.sendResponse(exchange, 200, response);
        } else {
            String response = JsonUtil.toJson(Map.of("error", "Category not found"));
            HttpUtil.sendResponse(exchange, 404, response);
        }
    }

    private void handleCreateCategory(HttpExchange exchange) throws IOException, SQLException {
        String requestBody = HttpUtil.getRequestBody(exchange);
        Category category = JsonUtil.fromJson(requestBody, Category.class);
        
        try {
            Category createdCategory = categoryService.createCategory(category);
            String response = JsonUtil.toJson(createdCategory);
            HttpUtil.sendResponse(exchange, 201, response);
        } catch (IllegalArgumentException e) {
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 400, response);
        }
    }

    private void handleUpdateCategory(HttpExchange exchange) throws IOException, SQLException {
        Long id = HttpUtil.extractIdFromPath(exchange.getRequestURI().getPath(), "/api/categories/(\\d+)/?");
        String requestBody = HttpUtil.getRequestBody(exchange);
        Category category = JsonUtil.fromJson(requestBody, Category.class);
        
        try {
            Category updatedCategory = categoryService.updateCategory(id, category);
            String response = JsonUtil.toJson(updatedCategory);
            HttpUtil.sendResponse(exchange, 200, response);
        } catch (IllegalArgumentException e) {
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 400, response);
        }
    }

    private void handleDeleteCategory(HttpExchange exchange) throws IOException, SQLException {
        Long id = HttpUtil.extractIdFromPath(exchange.getRequestURI().getPath(), "/api/categories/(\\d+)/?");
        
        try {
            boolean deleted = categoryService.deleteCategory(id);
            if (deleted) {
                HttpUtil.sendResponse(exchange, 204, "");
            } else {
                String response = JsonUtil.toJson(Map.of("error", "Failed to delete category"));
                HttpUtil.sendResponse(exchange, 500, response);
            }
        } catch (IllegalArgumentException e) {
            String response = JsonUtil.toJson(Map.of("error", e.getMessage()));
            HttpUtil.sendResponse(exchange, 400, response);
        }
    }
}